﻿namespace Rzrlf.SP.Innovator.WebParts.Utils
{
    internal class ControlUtil
    {
        internal static System.Web.UI.Control FindControlRecursivelyByClientId(System.Web.UI.Control root, string clientId)
        {
            if (root == null)
            {
                return null;
            }

            if (!string.IsNullOrEmpty(root.ClientID) && root.ClientID.Equals(clientId, System.StringComparison.OrdinalIgnoreCase))
            {
                return root;
            }

            foreach (System.Web.UI.Control child in root.Controls)
            {
                if (!string.IsNullOrEmpty(child.ClientID) && child.ClientID.Equals(clientId, System.StringComparison.OrdinalIgnoreCase))
                {
                    return child;
                }

                System.Web.UI.Control grandChild = FindControlRecursivelyByClientId(child, clientId);
                if (grandChild != null)
                {
                    return grandChild;
                }
            }

            return null;
        }

        internal static System.Web.UI.Control FindControlRecursivelyById(System.Web.UI.Control root, string id)
        {
            if (root == null)
            {
                return null;
            }

            if (!string.IsNullOrEmpty(root.ID) && root.ID.Equals(id, System.StringComparison.OrdinalIgnoreCase))
            {
                return root;
            }

            foreach (System.Web.UI.Control child in root.Controls)
            {
                if (!string.IsNullOrEmpty(child.ID) && child.ID.Equals(id, System.StringComparison.OrdinalIgnoreCase))
                {
                    return child;
                }

                System.Web.UI.Control grandChild = FindControlRecursivelyById(child, id);
                if (grandChild != null)
                {
                    return grandChild;
                }
            }

            return null;
        }
    }
}